<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <!--财务基本信息-->
      <div class="area-header">
        <span class="area-header-title">
          {{ $t('数据上传') }}
          <el-tooltip placement="top">
            <div slot="content">
              <span v-html="$t('1. 此页面财务数据录入页面；<br>')" />
              <span v-html="$t('2. 点击“下载Excel模板”链接，可下载最新财务数据Excel模板；<br>')" />
              <span v-html="$t('3. 同一公司不可重复录入同一“年份+报告周期”财务数据；<br>')" />
              <span v-html="$t('4. Excel文件和OCR财报识别只能上传一种；<br>')" />
              <span v-html="$t('5. OCR财报识别可以上传多张图片，多张图片如果数据有重叠，会覆盖之前的数据；<br>')" />
              <span v-html="$t('6. OCR财报识别最多可以上传3个，不能超过3个；<br>')" />
              <span v-html="$t('7. 导入财务数据时，系统自动和原财务模板匹配，有未匹配的科目时，将跳转到匹配列表中；<br>')" />
            </div>
            <i class="el-icon-question" />
          </el-tooltip>
        </span>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('选择公司')" prop="companyId">
            <el-select v-model="form.companyId" filterable clearable :placeholder="$t('请选择')" @change="selectTree()">
              <el-option
                v-for="item in companyOptions"
                :key="item.id"
                :label="item.companyName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('选择模板')" prop="typeId">
            <el-select v-model="form.typeId" :placeholder="$t('选择模板')" :disabled="tempTypeDisable" @change="asyncCmyTemp">
              <el-option
                v-for="dict in sysPcwTypeOptions"
                :key="dict.id"
                :label="$t(dict.name)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('年份')" prop="year">
            <DatePicker
              v-model="form.year"
              :disabled="isDisable"
              type="year"
              :placeholder="$t('年份')"
              @change="validatePcwData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('报告周期')" prop="type">
            <el-select v-model="form.type" :disabled="isDisable" :placeholder="$t('报告周期')" @change="validatePcwData">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('上传Excel文件')" class="uploadErr" prop="fileAttName">
            <el-button class="down" size="small" type="primary" @click="fetchTemplate()">{{ $t('下载Excel模板') }}</el-button>
            <el-upload
              v-if="!isDisable"
              ref="fileAttName"
              class="upload-demo"
              :headers="uploadHeaders"
              :action="excelBaseUrl"
              :show-file-list="true"
              :before-remove="beforeRemoveFile"
              :before-upload="beforeAvatarUpload"
              :on-success="excelUploadSuccess"
              :auto-upload="true"
              :file-list="excelFileList"
            >
              <el-button size="small" :disabled="isDisable" type="primary">{{ $t('上传Excel文件') }}</el-button>
            </el-upload>
            <el-button v-else size="small" :disabled="isDisable" type="primary">{{ $t('上传Excel文件') }}</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('OCR财报识别')" class="uploadErr" prop="fileAttName">
            <el-button v-if="!isDisable" size="small" type="primary" style="height: 32px;" @click="openOCRUploadBtn">{{ $t('OCR财报上传') }}</el-button>
            <el-button v-else size="small" :disabled="isDisable" type="primary">{{ $t('OCR财报上传') }}</el-button>
            <ul class="el-upload-list el-upload-list--text" style="margin-top: -13px; margin-left: 10px;">
              <li v-for="(file, index) in ocrFileListShow" :key="index" tabindex="0" class="el-upload-list__item is-uploading">
                <a class="el-upload-list__item-name">
                  <i class="el-icon-document" />
                  {{ file.name }}
                </a>
                <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-circle-check" />
                </label>
                <i class="el-icon-close" @click="delOcrShowFileList(file)" />
              </li>
            </ul>
          </el-form-item>
        </el-col>
      </el-row>

      <el-tabs v-model="view" class="noPad">
        <el-tab-pane :label="$t('财务科目信息')" name="dataBase" />
        <el-tab-pane :label="$t('关键指标信息')" name="dataKeys" />
      </el-tabs>
      <div v-if="view==='dataKeys'">
        <!--关键指标信息-->
        <div class="area-header">
          <span class="area-header-title">
            {{ $t('关键指标') }}
            <el-tooltip placement="top">
              <div slot="content">
                <span v-html="$t('1. 点击“新增”可创建新的关键指标；<br>')" />
                <span v-html="$t('2. 点击“选择公式”，可编辑修改指标公式；<br>')" />
                <span v-html="$t('3. 含公式的指标值系统将自动计算，不可修改；<br>')" />
                <span v-html="$t('4. 不含公式的指标值，用户需手动维护指标值；<br>')" />
                <span v-html="$t('5. 公司首次创建财务数据时，默认从系统设置中同步关键指标。<br>')" />
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
        </div>
        <el-table
          :data="form.dataKeys"
          row-key="id"
          default-expand-all
          border
        >
          <el-table-column :label="$t('分类')" width="160" align="left" prop="keyReport" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.pid === '0'">{{ $t(scope.row.keyReport) }}</span>
              <el-input v-if="!scope.row.id" v-model="scope.row.keyReport" :placeholder="$t('分类')" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('指标名称')" width="250" align="center" prop="keyName" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-if="scope.row.pid !== '0'" ref="keyName" v-model="scope.row.keyName" :placeholder="$t('指标名称')" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('公式')" align="right" prop="indicatorsFormula">
            <template slot-scope="scope">
              <div class="overflowText">
                <span v-if="scope.row.pid !== '0'" :title="formatGS(scope.row)" v-text="formatGS(scope.row)" />
                <a
                  v-if="scope.row.pid !== '0'"
                  class="link_a"
                  @click="selectGS(scope.row.dataId)"
                >{{ $t('选择公式') }}</a>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('值')" width="100" align="center" prop="keyValue">
            <template slot-scope="scope">
              <el-input v-if="scope.row.pid !== '0'" v-model="scope.row.keyValue" oninput="value=value.replace(/[^\d.]/g,'')" :readonly="scope.row.indicatorsFormula !== '' && scope.row.indicatorsFormula !== null" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('排序')" width="100" align="center" prop="sort">
            <template slot-scope="scope">
              <el-input v-if="scope.row.pid !== '0'" v-model="scope.row.sort" oninput="value=value.replace(/[^\d.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('操作')"
            align="center"
            width="100"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.keyName || !scope.row.id"
                :v-bind:v-has-permi="['company:financial:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="(e)=> delRowKey(scope.row)"
              >{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button size="small" type="primary" :disabled="isDisable" @click="addRowKey">{{ $t("新增") }}</el-button>
        </div>
      </div>
      <div v-if="view==='dataBase'">
        <!--基础数据-->
        <div class="area-header">
          <span class="area-header-title">
            {{ $t('基础数据') }}
            <el-tooltip placement="top">
              <div slot="content">
                <span v-html="$t('1. 保存财务数据后，系统会将导入的科目值展示到此模块中；<br>')" />
                <span v-html="$t('2. 此模块中的指标值可修改。<br>')" />
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
        </div>
        <div style="display: flex;width: 100%;">
          <div style="width: 33%;" class="bs">
            <el-table
              :data="form.bsList"
              border
              class="bs"
              default-expand-all
            >
              <el-table-column :label="$t('资产负债表')" width="100%" align="center" prop="bs">
                <el-table-column :label="$t('科目名称')" align="center" prop="keyName">
                  <template slot-scope="scope">
                    <span>{{ $t(scope.row.keyName) }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('值')" width="150" align="center" prop="keyValue">
                  <template slot-scope="scope">
                    <Money v-model="scope.row.keyValue" unit="" />
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
          <div style="width: 33%;" class="pd">
            <el-table
              :data="form.pdList"
              border
              class="pd"
              default-expand-all
            >
              <el-table-column :label="$t('利润表')" width="100%" align="center" prop="pd">
                <el-table-column :label="$t('科目名称')" align="center" prop="keyName">
                  <template slot-scope="scope">
                    <span>{{ $t(scope.row.keyName) }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('值')" width="150" align="center" prop="keyValue">
                  <template slot-scope="scope">
                    <Money v-model="scope.row.keyValue" unit="" />
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
          <div style="width: 33%;" class="cf">
            <el-table
              :data="form.cfList"
              border
              class="cf"
              default-expand-all
            >
              <el-table-column :label="$t('现金流量表')" width="100%" align="center" prop="cf">
                <el-table-column :label="$t('科目名称')" align="center" prop="keyName">
                  <template slot-scope="scope">
                    <span>{{ $t(scope.row.keyName) }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('值')" width="150" align="center" prop="keyValue">
                  <template slot-scope="scope">
                    <Money v-model="scope.row.keyValue" unit="" />
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-form>

    <el-dialog
      :title="$t('OCR上传PDF或图片')"
      :visible.sync="splitPdfOpen"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <div v-loading="uploadLoading">
        <el-upload
          ref="uploadSubmitBtn"
          class="upload-demo"
          drag
          :headers="uploadHeaders"
          :action="ocrBaseUrl"
          :show-file-list="true"
          :before-remove="beforeRemoveFile"
          :on-success="ocrUploadSuccess"
          :before-upload="beforeAvatarUploadOcr"
          :auto-upload="false"
          :on-exceed="onExceed"
          :limit="1"
          accept="pdf,jpg,png,jpeg"
          :data="{ 'startPage': (page.start === undefined ? '0' : page.start), 'endPage': (page.end === undefined ? '0' : page.end) }"
          style="color: #1890ff;"
          :file-list="ocrFileList"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red"> {{ $t('提示：仅支持图片和PDF件, 起始页和结束页只应用与PDF！') }}</div>
        </el-upload>
        <el-form ref="pageForm" :model="page" label-width="120px" class="dataForm">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="start" :rules="[{ required: false, validator: checkPage, trigger: 'blur' }]">
                <span slot="label">
                  {{ $t('PDF起始页') }}
                  <el-tooltip placement="top">
                    <div slot="content">
                      <span v-html="$t('识别起始页和结束页区间的PDF页面；<br>')" />
                      <span v-html="$t('1.不输入全部识别；<br>')" />
                      <span v-html="$t('2.只输入起始页, 从起始页开始识别至文档末；<br>')" />
                      <span v-html="$t('3.只输入结束页, 从第一页开始识别至结束页；<br>')" />
                    </div>
                    <i class="el-icon-question" style="margin-top: 10px; margin-right: 10px;" />
                  </el-tooltip>
                </span>
                <el-input-number v-model="page.start" :min="1" :max="9999" :placeholder="$t('从N页开始')" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('PDF结束页')" prop="end" :rules="[{ required: false, validator: checkPage, trigger: 'blur' }]">
                <el-input-number v-model="page.end" :min="1" :max="9999" :placeholder="$t('N页结束')" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="splitPdfOpen = false">{{ $t('取消') }}</el-button>
          <el-button size="small" type="primary" @click="submitFileForm">{{ $t('上传PDF或图片') }}</el-button>
        </div>
      </div>
    </el-dialog>

    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="company:pcw" />
    </div>
    <!-- 添加或修改关键指标公式（系统模板）对话框 -->
    <el-dialog :title="$t('选择公式')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogFormBox" append-to-body>
      <pcwTempKeyFormula ref="pcwTempKeyFormula" :company-id="form.companyId" :formula="formula" />
    </el-dialog>
    <!-- 科目匹配 -->
    <el-dialog :title="$t('科目匹配')" :visible.sync="matchFormOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <pcwDataMatchList ref="pcwDataMatchList" :company-id="form.companyId" />
    </el-dialog>
    <!-- 财报识别 -->
    <el-dialog :title="$t('财报识别结果')" :visible.sync="ocrFormOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <pcwOcrResult ref="pcwOcrResult" />
    </el-dialog>

    <!--预览附件-->
    <!--<OnlinePreview ref="OnlinePreview" />-->
  </div>
</template>

<script>
import { savePcwDataMain, getSubjectByCompanyId, validatePcwData } from '@/api/company/pcw/pcwDataMain'
import { delPcwDataKeys } from '@/api/company/pcw/pcwDataKeys'
import pcwTempKeyFormula from '@/views/company/pcw/pcwTempKeyFormula.vue'
import pcwDataMatchList from '@/views/company/pcw/pcwDataMatchList.vue'
import pcwOcrResult from '@/views/company/pcw/pcwOcrResult.vue'
import { Notification } from 'element-ui'
import { config } from '@/utils'
import { getToken } from '@/utils/auth'
import { listCompanyBase } from '@/api/company/base/companyBase'
import { dealListPcwSysType } from '@/api/company/pcw/pcwSysType'
import { getByCompanyId, asyncCmyTemp } from '@/api/company/pcw/pcwCmyInit'
export default {
  components: {
    pcwTempKeyFormula,
    pcwDataMatchList,
    pcwOcrResult
  },
  data() {
    return {
      // 表单参数
      form: {
        dataKeys: [],
        dataBases: [],
        cfList: [],
        pdList: [],
        bsList: []
      },
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        year: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        type: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 报告周期
      typeOptions: [],
      // 科目查询参数
      queryParams: {
        id: '',
        companyId: this.$route.query.companyId,
        year: '',
        type: ''
      },
      excelFileList: [],
      // 财报识别文件
      ocrFileList: [],
      ocrFileListShow: [],
      splitPdfOpen: false,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      formOpen: false,
      // 科目匹配弹出层标题
      matchTitle: '',
      // 科目匹配弹出层是否显示
      matchFormOpen: false,
      // 财报识别结果title
      ocrTitle: '',
      // 财报识别结果formOpen
      ocrFormOpen: false,
      // 选择公式的时候，数据的dataId,老数据对应的id，新数据会生成一个id
      dataId: '',
      // 展示视图
      view: 'dataBase',
      // 财报识别上传的文档的附件ID
      ocrAttIds: '',
      // 上传的EXCEL文件的福建ID
      excelAttIds: '',
      // 附件上传地址
      uploadHeaders: { Authorization: 'Bearer ' + getToken() },
      // excel后台上传地址
      ocrBaseUrl: config.baseURL + '/pcw/pcwDataMain/upload/pcwReportIdentify',
      // OCR后台上传地址
      excelBaseUrl: config.baseURL + '/pcw/pcwDataMain/upload/pcwExcelData',
      // 所有公司
      companyOptions: [],
      // 系统模板
      sysPcwTypeOptions: [],
      // 查询公司条件
      companyQueryParam: {
        companyId: ''
      },
      // 选择公司和模板之前，其他的输入框全部先不能录入数据
      isDisable: true,
      // 系统模板是否禁用
      tempTypeDisable: true,
      // 初始化模板form
      tempForm: {
        typeId: '',
        companyId: ''
      },
      page: {
        start: undefined,
        end: undefined
      },
      uploadLoading: false,
      formula: {}
    }
  },
  created() {
    // 财报周期
    this.getDicts('financial_type').then(response => {
      this.typeOptions = response.data
    })
    this.getCompanyList()
    this.initSysTypeOption()
  },
  methods: {
    // 初始化数据
    init(data) {
      this.ocrFileList = []
      this.ocrFileListShow = []
      if (this.form.companyId !== undefined && this.form.companyId !== null && this.form.companyId !== '') {
        this.isDisable = false
      }
      if (data != null && data !== '') {
        this.queryParams.id = data
      } else {
        this.queryParams.id = null
      }
      this.excelFileList = []
      getSubjectByCompanyId(this.queryParams).then(response => {
        this.checkCompanyTemp()
        if (response.data.id == null) {
          response.data.id = ''
          this.reset()
        } else {
          if (response.data.excelAttName !== null && response.data.excelAttName !== '') {
            const list = {
              name: response.data.excelAttName
            }
            this.excelFileList.push(list)
          }
          this.ocrFileList = response.data.listFileBase
          this.ocrFileListShow = response.data.listFileBase
        }
        this.form = response.data
        this.loading = false
      })
    },
    // 获取所有公司列表
    getCompanyList() {
      listCompanyBase(this.companyQueryParam).then(response => {
        this.companyOptions = response.rows
      })
    },
    // 获取系统所有的财务报表模板分类
    initSysTypeOption() {
      dealListPcwSysType(this.queryParams).then(res => {
        this.sysPcwTypeOptions = res.rows
      })
    },
    // 格式化公式
    formatGS(row) {
      if (row.indicatorsFormula === '' || row.indicatorsFormula === null) {
        return ''
      }
      return this.$t(row.indicatorsFormula)
    },
    // 生成随机ID
    createRomdomId() {
      var str = []
      var Chars = '0123456789abcdefghijklmnopqrstuvwxyz'
      for (var i = 0; i < 36; i++) {
        str[i] = Chars.substr(Math.floor(Math.random() * 16), 1)
      }
      str[0] = str[8] = str[13] = str[18] = str[23] = '-'
      return str.join('')
    },
    // 添加关键指标
    addRowKey() {
      const row = {
        id: '',
        keyReport: '',
        keyName: '',
        indicatorsFormula: '',
        indicatorsCodeFormula: '',
        keyValue: '',
        sort: '',
        dataId: this.createRomdomId()
      }
      if (!(this.form.dataKeys instanceof Array)) {
        this.$set(this.form, 'dataKeys', [])
      }
      this.$nextTick(() => {
        this.form.dataKeys.push(row)
      })
    },
    // 删除关键指标
    delRowKey(row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            // return getDataById(id)
          }).then(() => {
          this.searchOption(row, this.form.dataKeys)
          this.deleteKeyForEach()
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {})
      } else {
        this.searchOption(row, this.form.dataKeys)
        this.deleteKeyForEach()
      }
    },
    // 递归查找
    searchOption(row, datakeys, type = 'delect') {
      for (let s = 0; s < datakeys.length; s++) {
        if (datakeys[s].id === row.id) {
          if (type === 'delect') {
            datakeys.splice(s, 1)
            if (this.form.id !== null && this.form.id !== '') {
              return delPcwDataKeys(row.id)
            }
          }
          break
        } else if (datakeys[s].children && datakeys[s].children.length > 0) { // 递归条件
          this.searchOption(row, datakeys[s].children)
        }
      }
    },
    // 删除之后，遍历指标集合，如果他的children size = 0，删除这个指标
    deleteKeyForEach() {
      let idx = 0
      this.form.dataKeys.forEach(item => {
        if (item.children.length === 0) {
          this.form.dataKeys.splice(idx, 1)
        }
        idx++
      })
    },
    // 上传附件之前验证附件后缀和大小
    beforeAvatarUpload(file) {
      // 上传之前先验证是否已经上传了OCR文件，如果已经上传了，则提示或者要求删除OCR文件
      if (this.ocrFileListShow.length > 0) {
        this.msgError(this.$t('已经上传了OCR文件，请删除OCR文件之后再上传Excel文件！'))
        return false
      }
      let filename = file.name
      filename = filename.substr(filename.lastIndexOf('.'))
      const isXLSX = filename === '.xlsx'
      const isXLS = filename === 'xls'

      if (!isXLSX && !isXLSX) {
        this.$message.error(this.$t('上传文件必须是EXCEL xlsx/xls 格式!'))
        return false
      }
      return (isXLSX || isXLS)
    },
    openOCRUploadBtn() {
      if (this.ocrFileListShow !== undefined && this.ocrFileListShow.length >= 3) {
        this.msgError('最多支持上传三张!')
      } else {
        this.splitPdfOpen = true
        this.ocrFileList = []
      }
    },
    delOcrShowFileList(file) {
      this.ocrFileListShow && this.ocrFileListShow.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.ocrFileListShow.splice(index, 1)
        }
      })
    },
    onExceed() {
      this.msgError(this.$t('每次仅支持识别一个文件!'))
    },
    submitFileForm() {
      this.$refs.uploadSubmitBtn.submit()
    },
    // 财报识别上传附件之前验证附件后缀和大小
    beforeAvatarUploadOcr(file) {
      // 上传之前先验证是否已经上传了Excel文件，如果已经上传了，则提示或者要求删除excel文件
      if (this.excelFileList.length > 0) {
        this.msgError(this.$t('已经上传了Excel文件，请删除Excel文件之后再上传OCR财报识别！'))
        return false
      }
      let filename = file.name
      filename = filename.substr(filename.lastIndexOf('.'))
      const isPDF = filename === '.pdf'
      const isJPG = filename === '.jpg'
      const isPNG = filename === '.png'
      const isGIF = filename === '.gif'
      const isTMP = filename === '.tmp'

      if (!isPDF && !isJPG && !isPNG && !isGIF && !isTMP) {
        this.$message.error(this.$t('上传文件必须是pdf或者图片格式!'))
      }
      const uploadFlag = (isPDF || isJPG || isPNG || isGIF || isTMP)
      if (uploadFlag) {
        if (this.ocrFileListShow.length >= 3) {
          this.msgError(this.$t('最多上传三个ORC财报文件!'))
          return false
        } else {
          this.uploadLoading = true
        }
      }
      return uploadFlag
    },
    // Excel文件上传成功，触发此函数
    excelUploadSuccess(resp, file, fileList) {
      this.loading = true
      if (resp.code === 200) {
        this.excelFileList = [file]
        this.excelAttIds = resp.datas.attId
        this.openPcwOcr(resp)
        // 判断是否有匹配科目
      } else {
        // 删除附件
        fileList.splice(fileList.length - 1, 1)
        this.msgError(resp.msg)
      }
      this.loading = false
    },
    // OCR文件上传成功，触发此函数
    ocrUploadSuccess(resp, file, fileList) {
      if (resp.code === 200) {
        this.ocrFileListShow.push(file)
        this.page.start = undefined
        this.page.end = undefined
        this.ocrAttIds += ',' + resp.datas.attId
        this.openPcwOcr(resp)
        this.splitPdfOpen = false
        // 判断是否有匹配科目
      } else {
        // 删除附件
        fileList.splice(fileList.length - 1, 1)
        this.msgError(resp.msg)
      }
      this.uploadLoading = false
    },
    // 财务识别完成之后打开财务识别弹窗
    openPcwOcr(resp) {
      this.ocrFormOpen = true
      this.$nextTick(() => {
        this.$refs.pcwOcrResult.form.pdList = resp.datas.pdList
        this.$refs.pcwOcrResult.form.cfList = resp.datas.cfList
        this.$refs.pcwOcrResult.form.bsList = resp.datas.bsList
        this.$refs.pcwOcrResult.source = 'cmy'
      })
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/financialDataImportTemplate.xlsx'
    },
    // 选择公式操作
    selectGS(dataId) {
      this.dataId = dataId
      this.formOpen = true
      this.formula = {
        name: this.form.indicatorsFormula,
        code: this.form.indicatorsCodeFormula
      }
    },
    // 回显公式
    addFormula(name, code) {
      this.diGuiFormula(name, code, this.form.dataKeys)
    },
    // 递归判断dataId是否匹配，匹配回显
    diGuiFormula(name, code, datakeys) {
      for (let s = 0; s < datakeys.length; s++) {
        if (datakeys[s].dataId === this.dataId) {
          datakeys[s].indicatorsFormula = name
          datakeys[s].indicatorsCodeFormula = code
        } else if (datakeys[s].children && datakeys[s].children.length > 0) {
          this.diGuiFormula(name, code, datakeys[s].children)
        }
      }
    },
    // 验证同一公司下面，不能出现同一年度+同一报告周期的财务报表
    validatePcwData() {
      this.queryParams.year = this.form.year
      this.queryParams.type = this.form.type
      this.queryParams.companyId = this.form.companyId
      if (this.queryParams.year !== undefined && this.queryParams.year !== '' && this.queryParams.type !== undefined && this.queryParams.type !== '') {
        validatePcwData(this.queryParams).then(res => {
          if (res.data === null) {
            this.form.type = ''
            Notification.error({
              title: res.msg
            })
          }
        })
      }
    },
    // 科目匹配之后，关闭窗口
    closeOpen() {
      this.matchTitle = ''
      this.matchFormOpen = false
      this.init(this.form.id)
      this.view = 'dataKeys'
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        companyId: this.$route.query.companyId,
        year: undefined,
        type: undefined,
        excelFileId: undefined,
        pdfFileId: undefined,
        excelFileList: [],
        ocrFileList: [],
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        dataBases: [],
        dataKeys: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      this.$parent.$parent.getList()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== null && this.form.id !== '' && this.form.id !== undefined) {
            if (this.excelFileList.length === 0 && this.ocrFileListShow.length === 0) {
              this.msgError(this.$t('请上传Excel文件或者上传PDF文件'))
              return
            }
            this.ocrFileList = this.ocrFileListShow
            if (this.form.pdList.length === 0 && this.form.cfList.length === 0 && this.form.bsList.length === 0) {
              this.msgError(this.$t('请上传文件获取科目数据！'))
              return
            }
          } else {
            this.form.pdfFileId = this.ocrAttIds !== '' ? this.ocrAttIds.substring(1) : ''
            this.form.excelFileId = this.excelAttIds
          }
          this.setDataBaseData()
          this.loading = true
          savePcwDataMain(this.form).then(response => {
            if (response.code === 200) {
              this.loading = false
              // 判断是否有匹配科目
              if (response.data !== '' && response.data !== null && response.data.length > 0) {
                this.form.id = response.datas.id
                this.matchFormOpen = true
                this.$nextTick(() => {
                  this.$refs.pcwDataMatchList.init(response.data)
                })
              } else {
                this.msgSuccess(this.$t('保存成功'))
                this.init(response.datas.id)
                this.view = 'dataKeys'
              }
            } else {
              this.msgError(response.msg)
            }
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 将科目子表数据放入到主表中
    setDataBaseData() {
      // 资产负债表数据
      if (this.form.bsList != null && this.form.bsList.length > 0) {
        this.form.bsList.forEach(item => {
          this.form.dataBases.push(item)
        })
      }
      // 现金流量表数据
      if (this.form.cfList != null && this.form.cfList.length > 0) {
        this.form.cfList.forEach(item => {
          this.form.dataBases.push(item)
        })
      }
      // 收益表数据
      if (this.form.pdList != null && this.form.pdList.length > 0) {
        this.form.pdList.forEach(item => {
          this.form.dataBases.push(item)
        })
      }
    },
    // 删除文件之前验证，是否可以删除
    beforeRemoveFile() {
      if (this.form.id !== undefined && this.form.id !== '' && this.form.id !== null) {
        this.msgError(this.$t('当前文件的数据已经参数了计算，不能删除！'))
        return false
      }
      return true
    },
    // 选择公司事件
    selectTree() {
      // this.form.companyId = val.id
      // this.form.typeId = ''
      this.checkCompanyTemp()
    },
    // 选择项目之后，验证当前项目是否已经选择过了模板
    checkCompanyTemp() {
      this.loading = true
      this.companyQueryParam.companyId = this.form.companyId
      getByCompanyId(this.companyQueryParam).then(res => {
        if (res.data === null) {
          // 如果没有选择模板，则选择模板的下拉框取消“禁用”，展示系统默认模板
          this.tempTypeDisable = false
        } else {
          this.form.typeId = res.data.typeId
          this.tempTypeDisable = true
          this.isDisable = false
          this.initKeys()
        }
        this.loading = false
      })
    },
    // 同步当前公司的财务模板
    asyncCmyTemp() {
      if (this.form.typeId === null || this.form.typeId === '') {
        this.msgError(this.$t('请选择财务分类模板!'))
      } else {
        this.loading = true
        this.tempForm.companyId = this.form.companyId
        this.tempForm.typeId = this.form.typeId
        asyncCmyTemp(this.tempForm).then(res => {
          if (res.code === 200) {
            this.msgSuccess(this.$t('初始化成功'))
            this.loading = false
            this.isDisable = false
            this.initKeys()
          }
        })
      }
    },
    // 初始化科目信息
    initKeys() {
      this.queryParams.companyId = this.form.companyId
      getSubjectByCompanyId(this.queryParams).then(response => {
        this.form.dataKeys = response.data.dataKeys
        this.loading = false
      })
    },
    checkPage(rule, value, callback) {
      if (this.page.start !== undefined && this.page.end !== undefined) {
        if (this.page.start > this.page.end) {
          callback(new Error(this.$t('页数输入不合理!')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
  }
}
</script>

<style scoped>
.dialogFormBox{
  width: 60% !important;
  height: 85%;
  overflow: hidden;
  top: 5% !important;
  margin-top: unset!important;
}
.dialogFormBox .el-dialog__body {
  height: calc(100% - 50px);
}
.dialogFormBox .el-dialog__body>div{
  position: relative;
  height: 100%;
  width: 100%;

}
.dialogFormBox .el-dialog__body>div .el-form{
  height: calc(100% - 50px);
  overflow: auto;
  position: absolute;
  top: 0;
  bottom: 70px;
  right: -20px;
  padding-right: 20px;
  left: 0;
}
.dialogFormBox .el-dialog__body>div .dialog-footer{
  position: absolute;
  bottom: 0;
  right: 0;
}

</style>
